package com.mallbook.controller.servlet.admin;

import com.mallbook.model.exception.CategoryExitsException;
import com.mallbook.model.exception.CategoryNameMaxException;
import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Category;
import com.mallbook.model.service.CategoryService;
import com.mallbook.model.utils.ProxyFactory;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-06-29
 */
@WebServlet("/admin/category")
public class CategoryServlet extends HttpServlet {

    private CategoryService categoryService = ProxyFactory.getProxy(CategoryService.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String opr = req.getParameter("opr");
        if (opr == null) {
            req.getRequestDispatcher("/WEB-INF/admin/category_add.jsp").forward(req, resp);
            return;
        }
        switch (Objects.requireNonNull(opr)) {
            case "initAdd":
                doInitAdd(req, resp);
                break;
            case "add":
                doAdd(req, resp);
                break;
            case "del":
                doDel(req, resp);
                break;
            case "select":
                doSelect(req, resp);
                break;
            case "updateSelect":
                doUpdateSelect(req, resp);
                break;
            case "update":
                doUpdate(req, resp);
                break;
            case "shield":
                doShield(req, resp);
                break;
            case "check":
                doCheck(req, resp);
                break;
            case "sort":
                doSort(req, resp);
                break;
        }
    }

    private void doSort(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        JSONObject jsonObject=new JSONObject();
        PrintWriter writer=resp.getWriter();
        String subjectIds=req.getParameter("subjectIds");
        String[] subjectIdArray = subjectIds.split(",");
        for (int i = 0; i < subjectIdArray.length; i++)
        {
            try {
                //根据ID修改 序号，序号就是i
                categoryService.updateSortById(i,Integer.parseInt(subjectIdArray[i]));
                jsonObject.put("msg","ok");
            }catch (ServiceException e){
                e.printStackTrace();
                jsonObject.put("msg","no");
            }
        }
        writer.print(jsonObject);
        writer.close();
    }

    private void doCheck(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        String name = req.getParameter("name");
        if (name.isEmpty()) {
            writer.print("类别名不能为空");
            writer.close();
        }else {
            if (name.length()<2||name.length()>5){
                writer.print("类别名长度应为2~5");
                writer.close();
                return;
            }
            Boolean flag = categoryService.isExit(name);
            if (flag){
                writer.print("类别名已存在");
            }else {
                writer.print("ok");
            }
            writer.close();
        }
    }

    /**
     * 批量屏蔽
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doShield(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids");
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            list.add(Integer.parseInt(ids[i]));
        }
        try {
            categoryService.displayCategoryMore(list, -1);
        } catch (ServiceException e) {
            e.printStackTrace();
            resp.getWriter().write("系统维护中");
        }
        resp.sendRedirect("category?opr=select");
    }

    /**
     * 修改
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String categoryDisplay = req.getParameter("display");
        String name = req.getParameter("name");
        JSONObject jsonObject = new JSONObject();
        String categoryName = null;
        if (name != null) {
            categoryName = name;
            if (categoryName.length() > 5 || categoryName.length() < 2) {
                jsonObject.put("msg", "名字长度应该为2-5");
                resp.getWriter().print(jsonObject);
                return;
            }
        }
        String categoryDel = req.getParameter("isDel");
        String categoryID = req.getParameter("cid");
        int isDisplay;
        if ("1".equals(categoryDisplay)) {
            isDisplay = 1;
        } else {
            isDisplay = -1;
        }
        int isDel;
        if ("-1".equals(categoryDel)) {
            isDel = -1;
        } else {
            isDel = 1;
        }
        try {
            categoryService.update(categoryName, null, isDisplay, isDel, Integer.parseInt(categoryID));
            jsonObject.put("msg", "ok");
            resp.getWriter().print(jsonObject);
//            resp.sendRedirect("category?opr=select");
        } catch (CategoryExitsException e) {
            e.printStackTrace();
            jsonObject.put("msg", "该类别已存在");
            resp.getWriter().print(jsonObject);
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中");
            resp.getWriter().print(jsonObject);
        }
    }

    /**
     * 修改前查询该数据展示
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doUpdateSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String cid = req.getParameter("id");
        JSONObject jsonObject = new JSONObject();
        try {
            Category category = categoryService.getCategoryById(Integer.parseInt(cid));
            // 存入json格式数据

            jsonObject.put("name", category.getCategoryName());
            jsonObject.put("isDel", category.getState());
            jsonObject.put("isDisplay", category.getIsDisplay());
            jsonObject.put("id", category.getId());
            resp.getWriter().print(jsonObject);
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg","系统维护中");
            resp.getWriter().print(jsonObject);
        }
    }

    /**
     * 查询所有数据
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        try {
            List<Category> categoryList = categoryService.getAllCategory();
            req.setAttribute("categoryList", categoryList);
            req.getRequestDispatcher("/WEB-INF/admin/category_list.jsp").forward(req, resp);
        } catch (ServiceException e) {
            e.printStackTrace();
            resp.getWriter().write("系统维护中");
        }

    }

    /**
     * 删除数据
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids");
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            list.add(Integer.parseInt(ids[i]));
        }
        try {
            categoryService.delCategoryMore(list);
        } catch (ServiceException e) {
            e.printStackTrace();
            resp.getWriter().write("系统维护中");
        }
        resp.sendRedirect("category?opr=select");
    }

    /**
     * 添加数据
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String categoryName = new String(req.getParameter("name").getBytes("iso8859-1"), StandardCharsets.UTF_8);
        String categoryDisplay = req.getParameter("display");
        JSONObject jsonObject = new JSONObject();
        int display;
        if ("1".equals(categoryDisplay)) {
            display = Integer.parseInt(categoryDisplay);
        } else {
            display = -1;
        }
        resp.setContentType("text/html;charset=UTF-8");
        try {
            categoryService.addCategory(categoryName, display);
            jsonObject.put("msg","ok");
            resp.getWriter().print(jsonObject);

        } catch (CategoryExitsException e) {
            jsonObject.put("msg","该类别已存在");
            resp.getWriter().print(jsonObject);

        } catch (CategoryNameMaxException e) {
            jsonObject.put("msg","类别名长度为2-5个字符");
            resp.getWriter().print(jsonObject);

        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg","系统维护中");
            resp.getWriter().print(jsonObject);
        }
    }

    /**
     * 初始化添加页面
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doInitAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/admin/category_add.jsp").forward(req, resp);
    }
}
